﻿using Business;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using MvcAppWeb.Models;

namespace MvcAppWeb.Controllers
{
    public class OrderCheckController : Controller
    {
        //
        // GET: /OrderCheck/
        static OrderList list;
        public ActionResult OrderCheck()
        {
            //if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            //else
            //{
            //    AppUserList model = (AppUserList)Session["UserInfo"];
            //    return View(model);
            //}
            return View();
        }
        public JsonResult Query(DateTime? startDate, DateTime? endDate, string tableName)
        {
            list = new OrderList();
            if (!startDate.HasValue || !endDate.HasValue)
                return Json("");
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;

            string strWhere = "  where  OrderTime>= to_date('" + startDate.Value + "','yyyy-mm-dd hh24:mi:ss')and OrderTime<=to_date('" + endDate.Value + "','yyyy-mm-dd hh24:mi:ss')";
            string strWhereMySql = "  where  add_time>=" + ConvertDateTimeInt(startDate.Value) + " and add_time<=" + ConvertDateTimeInt(endDate.Value);
            OrderService os = new OrderService();

            var mianOrder = os.GetMainOrderList<EscOrders>(OrderTableEnum.ESCORDERINFO, strWhereMySql);//主库订单数

            List<SalesApp> saleOrder;
            if (tableName == "SaleApp")
                saleOrder=os.GetMainOrderList<SalesApp>(OrderTableEnum.SALEAPP, strWhere);//ERP库订单数
            else
                saleOrder = os.GetMainOrderList<SalesApp>(OrderTableEnum.SALEORDER, strWhere);//ERP库订单数

            var validOrder = mianOrder.Where(x => ("156").Contains(x.ORDER_STATUS));//主库有效订单

            //int tempCount = validOrder.Count() - saleOrder.Count();
            //int OrderMissCount = tempCount<=0?0:tempCount;
            //156
            //var OrderMiss = from m in mianOrder
            //                join n in saleOrder
            //                on m.ORDER_SN equals n.SHEETID
            //                //where !saleOrder.Any(x => x.SHEETID == m.ORDER_SN)
            //                where !("156").Contains(m.ORDER_STATUS)
            //                select m;
            list.OrderMiss = from m in validOrder
                             where  !saleOrder.Any(x => x.SHEETID == m.ORDER_SN)
                             select m;

            list.OrderStutsDiff=from m in saleOrder where 
                                 !validOrder.Any(x => x.ORDER_SN == m.SHEETID)
                                 select  new EscOrders {
                                     ORDER_STATUS = GetESCDBStatus(m.SALEORDERFLAG),
                               ORDER_SN=m.SHEETID,
                              BEST_TIME = m.RATIONDATE.ToShortDateString() + " " + GetBestTime(m.RATIONTIME)
                             };
                                
            //var diffOrder = mainOrder.Select(x => x.ORDER_SN).Except(saleOrder.Select(x => x.SHEETID));//漏单数
           
            //WoChuCookie.AddCookie<IEnumerable<EscOrders>>("OrderMiss", list.OrderMiss, DateTime.Now.AddHours(1));//查询结果集保存到cookie中，默认缓存1小时
            //WoChuCookie.RemoveCookie("OrderMiss");
            //WoChuCookie.AddCookie("OrderMiss", Serialization<List<EscOrders>>(list.OrderMiss), DateTime.Now.AddHours(1));
            
            int OrderStutsDiffCount = 0; //状态不差异数
            int OrderDistributionCount = 0;//配送时间差异数
            int OrderDetailCount = 0;//订单明细差异数
           
            foreach (var item in saleOrder)
            {
                var tempOrder = mianOrder.FirstOrDefault(x => x.ORDER_SN == item.SHEETID);
                if (tempOrder != null)
                {
                    ////验证状态
                    //if (tempOrder.ORDER_STATUS != GetESCDBStatus(item.SALEORDERFLAG))
                    //{
                    //    OrderStutsDiffCount += 1;
                    //    list.StutsDiffAddOrder(tempOrder);
                    //}
                    //验证配送时间
                    if (!ValidBestTime(tempOrder.BEST_TIME, item.RATIONDATE, item.RATIONTIME))
                    {
                        OrderDistributionCount += 1;
                        list.DistributionDiffAddOrder(tempOrder);
                    }

                    //验证商品详细
                    //if (!mianOrder.Any(x => x.ORDER_SN == item.SHEETID && x.ORDER_STATUS == GetESCDBStatus(item.SALEORDERFLAG)))
                    //    OrderDetailCount += 1;
                }
            }
            
            //WoChuCookie.AddCookie("OrderStutsDiff", Serialization<List<EscOrders>>(list.OrderStutsDiff), DateTime.Now.AddHours(1));
            //WoChuCookie.AddCookie("OrderDistributionDiff", Serialization<List<EscOrders>>(list.OrderDistribution), DateTime.Now.AddHours(1));
           
            Dictionary<string, object> json = new Dictionary<string, object>();
            List<OrderSumResultModel> resultList = new List<OrderSumResultModel>();
            resultList.Add(new OrderSumResultModel
            {
                OrderMissCount = list.OrderMiss.Count(),
                OrderStutsDiffCount =list.OrderStutsDiff.Count(),
                OrderDetailCount = OrderDetailCount,
                OrderDistributionCount = OrderDistributionCount
            });

            json.Add("total", 0);
            json.Add("rows", resultList);

            return Json(json, JsonRequestBehavior.AllowGet);
        }


        public JsonResult QueryDiffOrders(int type)
        {
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;
            List<EscOrders> resutList = new List<EscOrders>();
            switch (type)
            { 
             
                case 1:
                    //resutList =Deserialize<List<EscOrders>>(WoChuCookie.GetCookieValue("OrderMiss"));
                    resutList = list.OrderMiss.Skip((page - 1) * rows).Take(rows).ToList();
                    total = list.OrderMiss.Count();
                   break;
                case 2:
                   resutList = list.OrderStutsDiff.Skip((page - 1) * rows).Take(rows).ToList();
                   total = list.OrderStutsDiff.Count();
                   break;
                case 3:
                   resutList = list.OrderDistribution.Skip((page - 1) * rows).Take(rows).ToList();
                   total = list.OrderDistribution.Count();
                   break;
                default:
                   resutList = null;
                   break;
            }
           
            Dictionary<string, object> json = new Dictionary<string, object>();

            json.Add("total", total);
            json.Add("rows", resutList);

            return Json(json, JsonRequestBehavior.AllowGet);
        }

        #region 辅助方法

        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name=”timeStamp”></param>
        /// <returns></returns>
        private DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
        }

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name=”time”></param>
        /// <returns></returns>
        private int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        private string GetESCDBStatus(string flag)
        {
            //switch (flag) { 
            //    case 0:
            //        return 0;

            //}
            if(flag=="0")
                return "0";
            if (flag == "10" || flag == "20" || flag == "30" || flag == "40")
                return "1";
            if (flag == "50")
                return "2";
            if (flag == "60")
                return "4";
            if (flag == "70")
                return "7";
            return "999";
        }

        private bool ValidBestTime(string ESCDate, DateTime SaleAPPDate, int temptime)
        {
            string[] temtESCDate = ESCDate.Split(' ');
            if (temptime == 0)
                if (temtESCDate[0] == SaleAPPDate.ToString("yyyy-MM-dd") && temtESCDate[1] == "09:00-12:30")
                    return true;
            if (temptime == 1)
                if (temtESCDate[0] == SaleAPPDate.ToString("yyyy-MM-dd") && temtESCDate[1] == "15:00-16:00")
                    return true;
            if (temptime == 2)
                if (temtESCDate[0] == SaleAPPDate.ToString("yyyy-MM-dd") && temtESCDate[1] == "16:00-17:00")
                    return true;
            if (temptime ==3)
                if (temtESCDate[0] == SaleAPPDate.ToString("yyyy-MM-dd")  && temtESCDate[1] == "17:00-18:00")
                    return true;
            if (temptime == 4)
                if (temtESCDate[0] == SaleAPPDate.ToString("yyyy-MM-dd")  && temtESCDate[1] == "18:00-19:00")
                    return true;
            if (temptime == 5)
                if (temtESCDate[0] == SaleAPPDate.ToString("yyyy-MM-dd")  && temtESCDate[1] == "19:00-20:00")
                    return true;
             return false;
        }
        private string GetBestTime(int temptime)
        {
             
            if (temptime == 0)
                return "09:00-12:30";
            if (temptime == 1)
                return "15:00-16:00";
            if (temptime == 2)
                return "16:00-17:00";
            if (temptime == 3)
                return "17:00-18:00";
            if (temptime == 4)
                return "18:00-19:00";
            if (temptime == 5)
                return "19:00-20:00";
            return "";
        }

        //对象序列化64位字符
        public string Serialization<T>(T value)
        {
            BinaryFormatter bf = new BinaryFormatter();  //声明一个序列化类

            MemoryStream ms = new MemoryStream();  //声明一个内存流

            bf.Serialize(ms, value);  //执行序列化操作

            byte[] result = new byte[ms.Length];

            result = ms.ToArray();

          return System.Convert.ToBase64String(result);
        }
        //反序列化对象
        public T Deserialize<T>(string value)
        {
            byte[] b = System.Convert.FromBase64String(value);  //将得到的字符串根据相同的编码格式分成字节数组

            MemoryStream ms = new MemoryStream(b, 0, b.Length);  //从字节数组中得到内存流

            BinaryFormatter bf = new BinaryFormatter();

            return (T)bf.Deserialize(ms);  //反序列化得到Person类对象
        }
        #endregion
    }
}
